import { useEffect } from 'react';
import { ToastProps } from './types';

export const Toast = ({ toast, onClose }: ToastProps) => {
  useEffect(() => {
    if (toast.duration) {
      const timer = setTimeout(() => {
        onClose(toast.id);
      }, toast.duration);
      
      return () => clearTimeout(timer);
    }
  }, [toast.id, toast.duration, onClose]);

  // 根据类型设置不同的背景颜色和图标
  const getToastStyles = () => {
    switch (toast.type) {
      case 'success':
        return {
          bgColor: 'bg-white',
          borderColor: 'border-green-500',
          iconColor: 'text-green-500',
          icon: '✓'
        };
      case 'error':
        return {
          bgColor: 'bg-white',
          borderColor: 'border-red-500',
          iconColor: 'text-red-500',
          icon: '✕'
        };
      case 'warning':
        return {
          bgColor: 'bg-white',
          borderColor: 'border-yellow-500',
          iconColor: 'text-yellow-500',
          icon: '⚠'
        };
      case 'info':
      default:
        return {
          bgColor: 'bg-white',
          borderColor: 'border-blue-500',
          iconColor: 'text-blue-500',
          icon: 'ℹ'
        };
    }
  };

  const styles = getToastStyles();

  return (
    <div 
      className={`
        ${styles.bgColor} border-l-4 ${styles.borderColor} shadow-lg rounded-sm
        min-w-[320px] max-w-md p-4 mb-3
        transform transition-all duration-500 ease-in-out
        ${(toast as any).closing ? 'animate-slide-out' : 'animate-slide-in'}
      `}
      role="alert"
    >
      <div className="flex items-start">
        <div className={`${styles.iconColor} mr-4 text-lg`}>
          {styles.icon}
        </div>
        <div className="flex-grow">
          <p className="font-bold">{toast.title}</p>
          <p className="text-sm text-gray-700">{toast.message}</p>
        </div>
        <button 
          onClick={() => onClose(toast.id)}
          className="ml-4 text-gray-400 hover:text-gray-600 transition-colors duration-200"
        >
          ✕
        </button>
      </div>
    </div>
  );
}; 